package com.dyc.course.sys.controller;

import com.dyc.course.common.annotation.SysLog;
import com.dyc.course.common.utils.R;
import com.dyc.course.common.validator.Assert;
import com.dyc.course.common.validator.ValidatorUtils;
import com.dyc.course.common.validator.group.AddGroup;
import com.dyc.course.common.validator.group.UpdateGroup;
import com.dyc.course.sys.entity.SysDeptEntity;
import com.dyc.course.sys.entity.SysUserEntity;
import com.dyc.course.sys.mapper.SysUserRoleMapper;
import com.dyc.course.sys.repository.SysUserRepository;
import com.dyc.course.sys.service.SysUserService;
import com.dyc.course.sys.shiro.ShiroUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.ArrayUtils;

import java.util.List;
import java.util.Map;
import java.util.Optional;

/**
 * 系统用户
 *
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController extends AbstractController {

	@Autowired
	private SysUserRepository repository;
	
	@Autowired
	private SysUserService sysUserService;
	
	@Autowired
	private SysUserRoleMapper sysUserRoleRepository;
	
	/**
	 * 所有用户列表
	 */
	@RequestMapping("/list")
	@RequiresPermissions("sys:user:list")
	public R list(@RequestParam Map<String, Object> params) {
		String page = (String) params.get("page");
		String size = (String) params.getOrDefault("limit", "10");
		String sortBy = (String) params.getOrDefault("sortBy", "userId");
		Sort sort = Sort.by(sortBy);
		PageRequest pageRequest = PageRequest.of(Integer.parseInt(page)-1, Integer.parseInt(size), sort);
		Page<SysUserEntity> entities;
		if (params.containsKey("username") && params.get("username").toString().length() > 0) {
			entities = repository.findByUsernameLike("%" + (String) params.get("username") + "%", pageRequest);
		} else {
			entities = repository.findAll(pageRequest);
		}
		return R.ok().put("page", entities);
	}
	
	/**
	 * 获取登录的用户信息
	 */
	@RequestMapping("/info")
	public R info() {
		return R.ok().put("user", getUser());
	}
	
	/**
	 * 修改登录用户密码
	 */
	@SysLog("修改密码")
	@RequestMapping("/password")
	public R password(String password, String newPassword) {
		Assert.isBlank(newPassword, "新密码不为能空");

		//原密码
		password = ShiroUtils.sha256(password, getUser().getSalt());
		//新密码
		newPassword = ShiroUtils.sha256(newPassword, getUser().getSalt());
				
		//更新密码
		boolean flag = sysUserService.updatePassword(getUserId(), password, newPassword);
		if (!flag) {
			return R.error("原密码不正确");
		}
		
		return R.ok();
	}
	
	/**
	 * 用户信息
	 */
	@RequestMapping("/info/{userId}")
	@RequiresPermissions("sys:user:info")
	public R info(@PathVariable("userId") Long userId) {
		Optional<SysUserEntity> optional = repository.findById(userId);
		SysUserEntity user = null;
		if (optional.isPresent()) {
			user = optional.get();
			if (user.getDept() != null) {
				user.setDeptId(user.getDept().getDeptId());
			}
			//获取用户所属的角色列表
			List<Long> roleIdList = sysUserRoleRepository.queryRoleIdList(userId);
			user.setRoleIdList(roleIdList);
		}
		return R.ok().put("user", user);
	}
	
	/**
	 * 保存用户
	 */
	@SysLog("保存用户")
	@RequestMapping("/save")
	@RequiresPermissions("sys:user:save")
	public R save(@RequestBody SysUserEntity user) {
		ValidatorUtils.validateEntity(user, AddGroup.class);
		if (user.getDeptId() != null) {
			SysDeptEntity dept = new SysDeptEntity();
			dept.setDeptId(user.getDeptId());
			user.setDept(dept);
		}
		sysUserService.saveUser(user);
		
		return R.ok();
	}
	
	/**
	 * 修改用户
	 */
	@SysLog("修改用户")
	@RequestMapping("/update")
	@RequiresPermissions("sys:user:update")
	public R update(@RequestBody SysUserEntity user) {
		ValidatorUtils.validateEntity(user, UpdateGroup.class);
		if (user.getDeptId() != null) {
			SysDeptEntity dept = new SysDeptEntity();
			dept.setDeptId(user.getDeptId());
			user.setDept(dept);
		}
		sysUserService.update(user);
		
		return R.ok();
	}
	
	/**
	 * 删除用户
	 */
	@SysLog("删除用户")
	@RequestMapping("/delete")
	@RequiresPermissions("sys:user:delete")
	public R delete(@RequestBody Long[] userIds) {
		if (ArrayUtils.contains(userIds, 1L)) {
			return R.error("系统管理员不能删除");
		}
		
		if (ArrayUtils.contains(userIds, getUserId())) {
			return R.error("当前用户不能删除");
		}

		for (Long id : userIds) {
			repository.deleteById(id);
		}
		
		return R.ok();
	}
	
}
